package opensocial.data.basic;

import java.sql.*;

import com.google.inject.*;
import com.google.inject.name.*;

@Singleton
public class SQLiteDatabaseGateway implements DatabaseGateway {
  
  private String connectionString;
  private static final String JDBC_DRIVER = "org.sqlite.JDBC";
  
  @Inject 
  public SQLiteDatabaseGateway(@Named("connection.string") String connectionString){
    this.connectionString = connectionString;
  }
  
  public Connection createConnection(){
    try{
      Class.forName(JDBC_DRIVER);
      return DriverManager.getConnection(connectionString);
    }catch(Exception e){
      throw new RuntimeException("Cannot create connection",e);
    }
  }

  @Override
  public void execute(String sql) {
    try{
      Connection cn = createConnection();
      PreparedStatement st = cn.prepareStatement(sql);
      st.execute();
      cn.close();
    }catch(Exception e){
      throw new RuntimeException("Cannot Create Statement for sql " + sql,e);
    }
  }

  @Override
  public int executeQuery(String sql, ResultSetCommand cmd) {
    try{
      Connection cn =  createConnection();
      PreparedStatement st = cn.prepareStatement(sql);
      int result = cmd.work(st.executeQuery());
      cn.close();
      return result;
    }catch(Exception e){
      throw new RuntimeException("Cannot Create Statement for sql " + sql,e);
    }
  }
}
